package com.ev.k3cloudBusiness.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ev.asl.constant.AslConstant;
import com.ev.common.enums.AuditStatusDict;
import com.ev.custom.domain.SupplierDO;
import com.ev.custom.service.SupplierService;
import com.ev.framework.utils.R;
import com.ev.framework.utils.ShiroUtils;
import com.ev.k3cloud.service.kingdeeMiddlewareService;
import com.ev.k3cloudBusiness.service.K3SupplierSynService;
import com.ev.k3cloudBusiness.vo.K3DeeSyncVO;
import com.ev.k3cloudBusiness.vo.K3MaterialResultsVo;
import com.ev.k3cloudBusiness.vo.K3SupplierResultsVo;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class K3SupplierSynServiceImpl implements K3SupplierSynService {
    @Autowired
    SupplierService supplierService;

    @Autowired
    kingdeeMiddlewareService       kingdeeMiddlewareService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R SupplierSyn() {
        //查询芯软云供应商
        List<SupplierDO> supplierDOS=supplierService.listAll();
        //调用K3Cloud供应商单据查询接口查询启用的供应商
        String supplierResult = kingdeeMiddlewareService.SupplierAll();

        K3DeeSyncVO<List<K3SupplierResultsVo>> kingdeeSyncVO = new Gson().fromJson(supplierResult,new TypeToken<K3DeeSyncVO<List<K3SupplierResultsVo>>>(){}.getType());

        if(!AslConstant.ZERO.equals(kingdeeSyncVO.getCode()))
        {
            log.info(kingdeeSyncVO.getMsg());
            return  R.error(kingdeeSyncVO.getMsg());
        }
        List<K3SupplierResultsVo> supplierResulitsVos = kingdeeSyncVO.getData();

        if(supplierResulitsVos.size() > 0)
        {
            long okAudit = AuditStatusDict.OK_AUDIT.getId();
            Long userId = ShiroUtils.getUserId();
            // 本地供应商代码
            List<Long> localIdList = supplierDOS.stream().map(SupplierDO::getId).collect(Collectors.toList());
            // K3Cloud供应商代码
            List<Long> remoteIdList = supplierResulitsVos.stream().map(K3SupplierResultsVo::getId).collect(Collectors.toList());
            // 删除的 k3无，本地有
            List<Long> deleteIdList = localIdList.stream().filter(e -> !remoteIdList.contains(e)).collect(Collectors.toList());
            // 修改的（本地库有的，远端库有的）
            List<Long> updateIdList = remoteIdList.stream().filter(localIdList::contains).collect(Collectors.toList());
            // 新增的（本地库无的，远端库有的）
            remoteIdList.removeAll(updateIdList);
            if(deleteIdList.size()>0)
            {
                //批量删除
                List<SupplierDO> supplierDOS1=supplierDOS.stream().filter(e->deleteIdList.contains(e.getId())).collect(Collectors.toList());
                for (SupplierDO supplierDO:supplierDOS1
                ) {
                    supplierDO.setDelFlag(1);
                }
                supplierService.batchUpdate(supplierDOS1);
                log.info("批量删除");
            }
            if(updateIdList.size()>0)
            {
                //批量更新
                List<K3SupplierResultsVo> supplierResulitsVoList = supplierResulitsVos.stream().filter(e -> updateIdList.contains(e.getId())).collect(Collectors.toList());
                List<SupplierDO> supplierDOS1=supplierDOS.stream().filter(e->updateIdList.contains(e.getId())).collect(Collectors.toList());
                K3SupplierResultsVo supplierResulitsVo;
                for (SupplierDO supplierDO:supplierDOS1
                ) {
                    supplierResulitsVo=supplierResulitsVoList.stream().filter(e->(supplierDO.getId().equals(e.getId()))).collect(Collectors.toList()).get(0);
                    //供应商名称
                    supplierDO.setName(supplierResulitsVo.getName());
                    //供应商代码
                    supplierDO.setCode(supplierResulitsVo.getNumber());
                    //组织代码
                    supplierDO.setOrgNumber(supplierResulitsVo.getBrNo());
                    supplierDO.setAuditId(userId);
                }
                supplierService.batchUpdate(supplierDOS1);
                log.info("批量更新");
            }
            if(remoteIdList.size()>0)
            {
                //批量插入
                List<K3SupplierResultsVo> stockResulitsVos= supplierResulitsVos.stream().filter(e -> remoteIdList.contains(e.getId())).collect(Collectors.toList());
                List<SupplierDO> supplierDOList= Lists.newArrayList();
                for (K3SupplierResultsVo supplierResulitsVo:stockResulitsVos
                ) {
                    SupplierDO supplierDO=new SupplierDO();
                    supplierDO.setId(supplierResulitsVo.getId());
                    //供应商姓名
                    supplierDO.setName(supplierResulitsVo.getName());
                    //供应商代码
                    supplierDO.setCode(supplierResulitsVo.getNumber());
                    //组织代码
                    supplierDO.setOrgNumber(supplierResulitsVo.getBrNo());
                    supplierDO.setDelFlag(0);
                    supplierDO.setStatus(okAudit);
                    supplierDO.setAuditId(userId);
                    supplierDO.setUseStatus(1);
                    supplierDOList.add(supplierDO);
                }
                supplierService.batchSave(supplierDOList);
                log.info("批量新增");
            }
        }
        return R.ok();
    }
}
